import argparse
import json
import matplotlib.pyplot as plt

class PlotArg:
    def __init__(self,plot=None,show=False,**kwargs):
        self.show = show
        self.parse_args(**kwargs)
        if not plot is None:
            plot(self)

    def parse_args(self,data='data.json',config='',figure=''):
        self.parser = argparse.ArgumentParser()
        self.parser.add_argument("data", nargs='?',default=data)
        self.parser.add_argument("-c","--config",default=config)
        self.parser.add_argument("-f","--figure",default=figure)
        self.parser.add_argument("-s","--show",action="store_true")
        self.parsed = self.parser.parse_args()
        self.load_data()

    def load_conf(self,default_conf=None):
        if self.parsed.config:
            self.conf = self.load_json(self.parsed.config)
        elif default_conf is None:
            self.conf = {}
        else:
            self.conf = default_conf
        return self.conf

    def load_data(self):
        self.data = self.load_json(self.parsed.data)
        self.apply_default('xvalue','x')
        self.apply_default('yvalue','y')

    def apply_default(self,gname,p):
        if gname not in self.data:
            return
        if 'series' not in self.data:
            return
        g = self.data[gname]
        for s in self.data['series']:
            if p not in s:
                s[p] = g

    def end(self):
        if self.parsed.figure:
            plt.savefig(self.parsed.figure)
        if self.parsed.show or self.show:
            plt.show()

    @staticmethod
    def load_json(fname):
        with open(fname,'rt') as f:
            data = json.loads(f.read())
        return data
    
    @staticmethod
    def save_json(fname,data):
        with open(fname,'wt') as f:
            print(json.dumps(data,indent=1),file=f)
            
        
